package com.woniuxy.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.annotation.MyLog;
import com.woniuxy.entity.Permission;
import com.woniuxy.service.permission.PermissionService;
import com.woniuxy.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
public class PermissionController {
    @Autowired
    private PermissionService permissionService;


    @MyLog("添加权限")
    @PostMapping("permission/save")
    public ResultVo save(@RequestBody Permission permission) {
        int rows = permissionService.save(permission);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }


    @MyLog("删除权限")
    @PostMapping("permission/delete")
    public ResultVo delete(@RequestBody String permissionId) {
        if (!StringUtils.hasText(permissionId)) {
            throw new RuntimeException("permissionId is required");
        }
        int rows = permissionService.delete(Integer.valueOf(permissionId));
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }


    @MyLog("修改权限")
    @PostMapping("permission/update")
    public ResultVo update(@RequestBody Permission permission) {
        int rows = permissionService.update(permission);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @PostMapping("permission/findAll")
    public ResultVo findAll() {
        List<Permission> list = permissionService.findAll();
        return ResultVo.success(list);
    }

    @PostMapping("permission/findOne")
    public ResultVo findOne(@RequestBody String permissionId) {
        if (!StringUtils.hasText(permissionId)) {
            throw new RuntimeException("permissionId is required");
        }
        Permission permission = permissionService.findOne(Integer.valueOf(permissionId));
        return ResultVo.success(permission);
    }

    @PostMapping("permission/findAllAsTree")
    public ResultVo findAllAsTree() {
        Permission root = permissionService.findRoot();
        return ResultVo.success(Arrays.asList(root));
    }


    @PostMapping("permission/findByPage")
    public ResultVo findByPage(@RequestBody Map<String, String> map) {
        String strPage = map.remove("page");
        String strSize = map.remove("size");
        PageInfo<Permission> permission = permissionService.findByPage(Integer.valueOf(strPage), Integer.valueOf(strSize));
        return ResultVo.success(permission);
    }
}
